package com.lengxf.pay.starter.parent.pay;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.google.common.io.CharStreams;
import com.lengxf.pay.common.bean.CallBackParam;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@AllArgsConstructor
public class PayBackParamConverter {

    private static final Log log = LogFactory.get();

    private HttpServletRequest request;

    public CallBackParam convert() {
        return new CallBackParam().setHeaderMap(getHeaderMap())
                .setQueryString(request.getQueryString())
                .setParameterMap(request.getParameterMap())
                .setBody(getBody(request));
    }

    private Map<String, String> getHeaderMap() {
        Map<String, String> headerMap = new HashMap<>();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            String headerValue = request.getHeader(headerName);
            headerMap.put(headerName, headerValue);
        }
        return headerMap;
    }

    private static String getBody(HttpServletRequest request) {
        try {
            return CharStreams.toString(request.getReader());
        } catch (IOException e) {
            log.error("回调报文解析异常 ....");
            throw new RuntimeException("回调报文解析异常");
        }
    }
}
